package com.jin.webvideo.base.spring.thymeleaf;

import com.jin.webvideo.base.LoginHandler;
import com.jin.webvideo.entity.SessionStore;
import com.jin.webvideo.util.base.StringUtil;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.context.WebEngineContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;
/**
 * thymeleaf  permission 标签 role 属性
 */
public class RoleProcessor extends AbstractAttributeTagProcessor {
    private static final String ATTR_NAME = "role";
    private static final int precedence = 1200;
    protected RoleProcessor(final String dialectPrefix) {
        super(TemplateMode.HTML, dialectPrefix, null, false, ATTR_NAME, true, precedence, true);
    }

    @Override
    protected void doProcess(ITemplateContext icontext, IProcessableElementTag iProcessableElementTag, AttributeName attributeName, String attrVal, IElementTagStructureHandler handler) {
        WebEngineContext context = (WebEngineContext)icontext;
        // 多角色分割
        String[] roles = StringUtil.split(attrVal, ",");
        SessionStore store = LoginHandler.getSessionStore(context.getSession());
        // 未登录 或 不是目标角色 移除标签（不显示）
        if ( store == null || !chkRole(store, roles)) {
            handler.removeElement();
        }
    }

    private boolean chkRole(SessionStore store, String[] roles) {
        return true;
    }
}
